///* 
// * Copyright (C) 2007 Google Inc.
// *
// * Licensed under the Apache License, Version 2.0 (the "License");
// * you may not use this file except in compliance with the License.
// * You may obtain a copy of the License at
// *
// *      http://www.apache.org/licenses/LICENSE-2.0
// *
// * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS,
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// * See the License for the specific language governing permissions and
// * limitations under the License.
// */
//
//package com.appit.loginandregister;
//
//import java.io.UnsupportedEncodingException;
//import java.net.URLEncoder;
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.Iterator;
//import java.util.List;
//import java.util.Set;
//import java.util.Timer;
//
//import javax.xml.parsers.ParserConfigurationException;
//import javax.xml.parsers.SAXParser;
//import javax.xml.parsers.SAXParserFactory;
//
//import org.apache.http.NameValuePair;
//import org.apache.http.message.BasicNameValuePair;
//import org.json.JSONArray;
//import org.json.JSONException;
//import org.json.JSONObject;
//import org.xml.sax.SAXException;
//
//import android.R;
//import android.app.Notification;
//import android.app.NotificationManager;
//import android.app.PendingIntent;
//import android.app.ProgressDialog;
//import android.app.Service;
//import android.content.Context;
//import android.content.Intent;
//import android.net.ConnectivityManager;
//import android.os.Binder;
//import android.os.IBinder;
//import android.support.v4.app.NotificationCompat;
//import android.util.Log;
//import android.widget.Toast;
//import at.vcity.androidim.interfaces.IAppManager;
//import at.vcity.androidim.interfaces.ISocketOperator;
//import at.vcity.androidim.interfaces.IUpdateData;
//import at.vcity.androidim.types.FriendInfo;
//import at.vcity.androidim.types.MessageInfo;
//
//import com.androidhive.dashboard.Advisor_Chat_Activity;
//import com.androidhive.dashboard.ChatActivity;
//import com.example.ufollocloudemail.AllEmailsActivity;
//import com.example.ufollocloudemail.JSONParser;
//import com.example.ufollocloudemail.MyApplication;
//import com.example.ufollocloudemail.NewEmailActivity;
//
//import database.helpers.Chats_Table;
//
//
//
//
///**
// * This is an example of implementing an application service that runs locally
// * in the same process as the application.  The {@link LocalServiceController}
// * and {@link LocalServiceBinding} classes show how to interact with the
// * service.
// *
// * <p>Notice the use of the {@link NotificationManager} when interesting things
// * happen in the service.  This is generally how background services should
// * interact with the user, rather than doing something more disruptive such as
// * calling startActivity().
// */
//public class IMService extends Service implements IAppManager, IUpdateData {
//	// private NotificationManager mNM;
//	public static String USERNAME;
//	public static final String TAKE_MESSAGE = "Take_Message";
//	public static final String FRIEND_LIST_UPDATED = "Take Friend List";
//	public static final String MESSAGE_LIST_UPDATED = "Take Message List";
//	public ConnectivityManager conManager = null; 
//	private final int UPDATE_TIME_PERIOD = 15000;
//	// private static final INT LISTENING_PORT_NO = 8956;
//	private String rawFriendList = new String();
//	private String rawMessageList = new String();
//
//	ISocketOperator socketOperator = new SocketOperator(this);
//
//	private final IBinder mBinder = new IMBinder();
//	private String username;
//	private String password;
//	private boolean authenticatedUser = false;
//	// timer to take the updated data from server
//	private Timer timer;
//	int count=0;
//	String login_value;
//	// Progress Dialog
//	private ProgressDialog pDialog;
//
//	// Creating JSON Parser object
//	JSONParser jParser = new JSONParser();
//
//	ArrayList<HashMap<String, String>> emailsList;
//
//	// url to get all products list
//	private static String url_all_products = "http://i-com.co.ug/ufollo/query_inbox.php";
//	// JSON Node names
//	private static final String TAG_SUCCESS = "success";
//	private static final String TAG_PRODUCTS = "inbox_main";
//	private static final String TAG_NAME = "rcontents";
//	private static final String TAG_FROM = "rfrom";
//
//	// products JSONArray
//	JSONArray products = null;
//
//	// private LocalStorageHandler localstoragehandler; 
//	private NotificationManager mNM;
//	private Chats_Table chaTab;
//
//	public class IMBinder extends Binder {
//		public IAppManager getService() {
//			return IMService.this;
//		}
//	}
//
//	@Override
//	public void onCreate() 
//	{   
//		emailsList = new ArrayList<HashMap<String, String>>();
//
//
//		// Loading products in Background Thread
//
//		// Bundle extras = ((Activity) getApplicationContext()).getIntent().getExtras();
//		// if(extras !=null) {
//		// login_value = extras.getString("new_variable_name");
//		// }
//
//		mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
//		final Boolean checkBackground =true;
//
//		//         localstoragehandler = new LocalStorageHandler(this);
//		// Display a notification about us starting.  We put an icon in the status bar.
//		//   showNotification();
//		conManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
//		//     new LocalStorageHandler(this);
//
//		// Timer is used to take the friendList info every UPDATE_TIME_PERIOD;
//		timer = new Timer();   
//		Thread thread = new Thread()
//		{
//			@Override
//			public void run() {
//
//				//socketOperator.startListening(LISTENING_PORT_NO);
//				String msqContent="nothing";
//				while (checkBackground)
//				{
//
//					try {
//						// Toast.makeText(getApplicationContext(), "sevice yaita", Toast.LENGTH_SHORT).show();
//						emailsList.clear();
//						queryServer();
//						// 
//						for (int i = 0; i < emailsList.size(); i++) {
//							String key;
//							Set <String> set_=emailsList.get(i).keySet();
//							Iterator<String> iter = set_.iterator();
//							while(iter.hasNext())
//							{
//								key=iter.next().toString();
//								msqContent= emailsList.get(i).get(key);
//								Log.i("tester", msqContent);
//								// System.println.o(msqContent);
//								if(ChatActivity.isOpen|| Advisor_Chat_Activity.isOpen)
//
//								{
//									Intent inn = new Intent();
//									inn.setAction("com.tutorialspoint.CUSTOM_INTENT");
//									// i.putExtra(MessageInfo.USERID, "friend");
//
//									inn.putExtra(MessageInfo.MESSAGETEXT, msqContent);
//									inn.putExtra(MessageInfo.SENDT, key);
//									sendBroadcast(inn);
//								}
//								else
//									showNotification(getApplicationContext(), key,msqContent);
//								// Toast.makeText(getApplicationContext(), msqContent, Toast.LENGTH_SHORT).show();
//							}
//							// 
//						}
//						Thread.sleep(5000);
//					} catch (InterruptedException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					}
//				}
//			}
//		};
//
//		thread.start();
//
//	}
//
//	private void queryServer() {
//		// TODO Auto-generated method stub
//		// String query_variable = MyApplication.getLoginVariable();
//		// Building Parameters
//		List<NameValuePair> params = new ArrayList<NameValuePair>();
//		params.add(new BasicNameValuePair("remail", "bullet"));
//		// getting JSON string from URL
//		JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
//		// Check your log cat for JSON reponse
//		Log.d("All Products: ", json.toString());
//
//		try {
//			// Checking for SUCCESS TAG
//			int success = json.getInt(TAG_SUCCESS);
//
//			if (success == 1) {
//				// products found
//				// Getting Array of Products
//				products = json.getJSONArray(TAG_PRODUCTS);
//
//				// looping through All Products
//				for (int i = 0; i < products.length(); i++) {
//					JSONObject c = products.getJSONObject(i);
//
//					// Storing each json item in variable
//					String contents = c.getString(TAG_NAME);
//					String from_ = c.getString(TAG_FROM);
//					// USERNAME=name;
//					// creating new HashMap
//					HashMap<String, String> map = new HashMap<String, String>();
//
//					// adding each child node to HashMap key => value
//					// map.put(TAG_PID, id);
//					map.put(from_,contents );
//
//					// adding HashList to ArrayList
//					emailsList.add(map);
//				}
//			} else {
//				// no products found
//				// Launch Add New product Activity
//				Intent i = new Intent(getApplicationContext(),
//						NewEmailActivity.class);
//				// // Closing all previous activities
//				// i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//				// startActivity(i);
//			}
//		} catch (JSONException e) {
//			e.printStackTrace();
//		}
//
//	}
//
//	/*
//    @Override
//    public void onDestroy() {
//        // Cancel the persistent notification.
//        mNM.cancel(R.string.local_service_started);
//
//        // Tell the user we stopped.
//        Toast.makeText(this, R.string.local_service_stopped, Toast.LENGTH_SHORT).show();
//    }
//	 */ 
//
//	@Override
//	public IBinder onBind(Intent intent) 
//	{
//		return mBinder;
//	}
//
//
//
//
//	/**
//	 * Show a notification while this service is running.
//	 * @param msg 
//	 **/
//	private void showNotification(String username, String msg) 
//	{       
//		// Set the icon, scrolling text and TIMESTAMP
//		String title = "AndroidIM: You got a new Message! (" + username + ")";
//
//		String text = username ;
//		//     + ": " +  
//		((msg.length() < 5) ? msg : msg.substring(0, 5)+ "...");
//
//		//NotificationCompat.Builder notification = new NotificationCompat.Builder(R.drawable.stat_sample, title,System.currentTimeMillis());
//		NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
//		//     .setSmallIcon(R.drawable.stat_sample)
//		.setContentTitle(title)
//		.setContentText(text); 
//
//
//
//		Intent i = new Intent(this, AllEmailsActivity.class);
//		//        i.putExtra(FriendInfo.USERNAME, username);
//		//        i.putExtra(MessageInfo.MESSAGETEXT, msg);
//
//
//		// The PendingIntent to launch our activity if the user selects this notification
//		PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
//				i, 0);
//
//		// Set the info for the views that show in the notification panel.
//		// msg.length()>15 ? MSG : msg.substring(0, 15);
//		mBuilder.setContentIntent(contentIntent); 
//
//		mBuilder.setContentText("New message from " + username + ": " + msg);
//
//		//TODO: it can be improved, for instance message coming from same user may be concatenated 
//		// next version
//
//		// Send the notification.
//		// We use a layout id because it is a unique number.  We use it later to cancel.
//		mNM.notify((username+msg).hashCode(), mBuilder.build());
//	}
//
//
//	private void showNotification(Context paramContext,String username, String msg ) {
//		NotificationManager  nm = (NotificationManager) paramContext.getSystemService(Context.NOTIFICATION_SERVICE);
//		// Get the text we passed in from ShiVa and place that text here in the message we are going to display to user
//		CharSequence message =msg ;
//		//        // Create a new pending intent called contentIntent
//		//        PendingIntent contentIntent = PendingIntent.getActivity(paramContext, 0, new Intent(), 0);
//		// Create a new notification which will include YOUR APP ICON
//		Notification notif = new Notification(android.R.drawable.alert_dark_frame, message, System.currentTimeMillis());
//		// Setup the notification window
//		//        notif.vibrate = new long[] {100,200,150}; 
//		//// 
//		//        notif.defaults = Notification.DEFAULT_ALL;
//		//        notif.defaults |= Notification.DEFAULT_SOUND;
//		//        notif.defaults |= Notification.DEFAULT_VIBRATE;
//
//		chaTab= new Chats_Table(paramContext);
//		CharSequence from = username;
//		chaTab.addCHATS(msg, "false");
//		chaTab.close();
//		Intent intent =new Intent(this, ChatActivity.class);
//		PendingIntent contentIntent = PendingIntent.getActivity(this, 0,intent , 0);
//		notif.setLatestEventInfo(paramContext, from, message, contentIntent);
//		// This flag here will INSISTENTLY send the notification to the user until the user ACKNOWLEDGES the notification by clicking on it
//		notif.flags = Notification.FLAG_INSISTENT;
//
//		// Clear the notification when it is pressed
//		notif.flags |= Notification.FLAG_AUTO_CANCEL;
//		// Stop the service when we are finished
//		stopSelf();
//		// This actually runs the notification command itself
//		nm.notify(1, notif);
//	}
//	public String getUsername() {
//		return this.username;
//	}
//
//	public String sendMessage(String  username, String  tousername, String message) throws UnsupportedEncodingException 
//	{
//
//		String params = "username="+ URLEncoder.encode(this.username,"UTF-8") +
//				"&password="+ URLEncoder.encode(this.password,"UTF-8") +
//				"&to=" + URLEncoder.encode(tousername,"UTF-8") +
//				"&message="+ URLEncoder.encode(message,"UTF-8") +
//				"&action="  + URLEncoder.encode("sendMessage","UTF-8")+
//				"&";
//
//		Log.i("PARAMS", params);
//		return socketOperator.sendHttpRequest(params);
//
//	}
//
//
//	/**
//	 * authenticateUser: it authenticates the user and if succesful
//	 * it returns the friend list or if authentication is failed 
//	 * it returns the "0" in string type
//	 * @throws UnsupportedEncodingException 
//	 * */
//	// public String authenticateUser(String usernameText, String passwordText) throws UnsupportedEncodingException 
//	// {
//	// this.username = usernameText;
//	// this.password = passwordText;
//
//	// 
//	// this.authenticatedUser = false;
//	// 
//	// String result = this.getFriendList(); //socketOperator.sendHttpRequest(getAuthenticateUserParams(username, password));
//	// if (result != null ) 
//	// {
//
//	// // if user is authenticated then return string from server is not equal to AUTHENTICATION_FAILED
//	// this.authenticatedUser = true;
//	// rawFriendList = result;
//	// USERNAME = this.username;
//	// Intent i = new Intent(FRIEND_LIST_UPDATED);
//
//	// i.putExtra(FriendInfo.FRIEND_LIST, rawFriendList);
//	// sendBroadcast(i);
//	// 
//	// timer.schedule(new TimerTask()
//	// {
//
//	// public void run() 
//	// {
//	// try {
//
//	// //rawFriendList = IMService.this.getFriendList();
//	// // sending friend list 
//	// Intent i = new Intent(FRIEND_LIST_UPDATED);
//	// Intent i2 = new Intent(MESSAGE_LIST_UPDATED);
//	// String tmp = IMService.this.getFriendList();
//	// String tmp2 = IMService.this.getMessageList();
//	// if (tmp != null) {
//	// i.putExtra(FriendInfo.FRIEND_LIST, tmp);
//	// sendBroadcast(i);
//
//	// Log.i("friend list broadcast sent ", "");
//	// 
//	// if (tmp2 != null) {
//	// i2.putExtra(MessageInfo.MESSAGE_LIST, tmp2);
//	// sendBroadcast(i2);
//
//	// Log.i("friend list broadcast sent ", "");
//	// }
//	// }
//	// else {
//	// Log.i("friend list returned null", "");
//	// }
//	// }
//	// catch (Exception e) {
//	// e.printStackTrace();
//	// }
//
//	// }
//
//	// }, UPDATE_TIME_PERIOD, UPDATE_TIME_PERIOD);
//	// }
//	// 
//	// return result;
//
//	// }
//
//	public void messageReceived(String username, String message) 
//	{
//
//		//FriendInfo friend = FriendController.getFriendInfo(username);
//		MessageInfo msg = MessageController.checkMessage(username);
//		if ( msg != null)
//		{
//
//			Intent i = new Intent(TAKE_MESSAGE);
//			i.setAction("com.tutorialspoint.CUSTOM_INTENT");
//			i.putExtra(MessageInfo.USERID, msg.userid);
//
//			i.putExtra(MessageInfo.MESSAGETEXT, msg.messagetext);
//
//			sendBroadcast(i);
//			// String activeFriend = FriendController.getActiveFriend();
//			// if (activeFriend == null || activeFriend.equals(username) == false) 
//			// {
//			// localstoragehandler.insert(username,this.getUsername(), message.toString());
//			showNotification(username, message);
//			// }
//			Log.i("TAKE_MESSAGE broadcast sent by im service", "");
//		}
//
//	}  
//	public void setUserKey(String value) 
//	{
//
//	}
//
//	public boolean isNetworkConnected() {
//		return conManager.getActiveNetworkInfo().isConnected();
//	}
//	public boolean isUserAuthenticated(){
//		return authenticatedUser;
//	}
//	public String getLastRawFriendList() {
//
//		return this.rawFriendList;
//	}
//	@Override
//	public void onDestroy() {
//		Log.i("IMService is being destroyed", "...");
//		super.onDestroy();
//	}
//	public void exit() 
//	{
//		timer.cancel();
//		socketOperator.exit(); 
//		socketOperator = null;
//		this.stopSelf();
//	}
//	public String signUpUser(String usernameText, String passwordText,
//			String emailText) 
//	{
//		String params = "username=" + usernameText +
//				"&password=" + passwordText +
//				"&action=" + "signUpUser"+
//				"&email=" + emailText+
//				"&";
//		String result = socketOperator.sendHttpRequest(params);
//
//		return result;
//	}
//
//	public String addNewFriendRequest(String friendUsername) 
//	{
//		String params = "username=" + this.username +
//				"&password=" + this.password +
//				"&action=" + "addNewFriend" +
//				"&friendUserName=" + friendUsername +
//				"&";
//
//		String result = socketOperator.sendHttpRequest(params);
//
//		return result;
//	}
//
//	public String sendFriendsReqsResponse(String approvedFriendNames,
//			String discardedFriendNames) 
//	{
//		String params = "username=" + this.username +
//				"&password=" + this.password +
//				"&action=" + "responseOfFriendReqs"+
//				"&approvedFriends=" + approvedFriendNames +
//				"&discardedFriends=" +discardedFriendNames +
//				"&";
//
//		String result = socketOperator.sendHttpRequest(params);
//
//		return result;
//	} 
//
//	public void updateData(MessageInfo[] messages,FriendInfo[] friends,
//			FriendInfo[] unApprovedFriends, String userKey) 
//	{
//		this.setUserKey(userKey);
//		//FriendController.
//
//		// MessageController.setMessagesInfo(messages);
//		//Log.i("MESSAGEIMSERVICE","messages.length="+messages.length);
//		int i = 0;
//		while (i < messages.length){
//			messageReceived(messages[i].userid,messages[i].messagetext);
//			//appManager.messageReceived(messages[i].userid,messages[i].messagetext);
//			i++;
//		}
//		// FriendController.setFriendsInfo(friends);
//		// FriendController.setUnapprovedFriendsInfo(unApprovedFriends);
//	}
//
//	@Override
//	public String authenticateUser(String usernameText, String passwordText)
//			throws UnsupportedEncodingException {
//		// TODO Auto-generated method stub
//		return null;
//	}
//
//
//}
